/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package lu.med.praxiswahl.wahlumed.dao.beans;

import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import lu.med.praxiswahl.wahlumed.dao.beans.daointerface.OrdonanceDAOInt;
import lu.med.praxiswahl.wahlumed.model.beans.CustomerTBL;
import lu.med.praxiswahl.wahlumed.model.beans.OrdonanceTBL;

/**
*
* @author Patrick kendzo
* Email: pkendzo@msn.com
*/

@Stateless
@Local( { OrdonanceDAOInt.class })
public class OrdonanceDAO implements OrdonanceDAOInt
{

	@PersistenceContext(unitName = "gynaekomedic-ejbPU")
	private EntityManager	em;

	public OrdonanceDAO()
	{
	}

	@Override
	public void delete(Long id)
	{
		OrdonanceTBL ord = em.find(OrdonanceTBL.class, id);
		
		CustomerTBL cust = ord.getCustomer();
		
		cust.getOrdonances().remove(ord);
		
		em.remove(ord);
		em.flush();

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<OrdonanceTBL> findCustomerOrdonancenBy_Typ_AND_Customer(String typ, String matricule)
	{
		try
		{

			List<OrdonanceTBL> resultList = (List<OrdonanceTBL>) em
					.createQuery(
							"select o from OrdonanceTBL o where o.typ = '"
									+ typ + "' and o.customer = '"+matricule+"' order by o.datum desc").getResultList();
			return resultList;
		}
		catch (Exception e)
		{
			throw new RuntimeException("Ordonance for this typ can be found ",
					e);
		}
	}

	@Override
	public void persist(OrdonanceTBL todo)
	{
		em.persist(todo);
		em.flush();

	}

	@Override
	public void update(OrdonanceTBL todo)
	{
		em.merge(todo);
		em.flush();

	}
	
	@Override
	public OrdonanceTBL retrieveOrdonanceTemplateByID(Long id) {
        return (OrdonanceTBL) em.find(OrdonanceTBL.class, id);
    }

	/*@Override
	public int findDatabaseSubPrimaryKeyIndex()
	{
		try
		{

			Integer result = new Integer(0);
			
			List<OrdonanceTBL> resultList = (List<OrdonanceTBL>)em
					.createQuery(
							"select o from OrdonanceTBL o ").getResultList();
			
			result = resultList.size();
			return result.intValue();
		}
		catch (Exception e)
		{
			throw new RuntimeException("Database is empty",
					e);
		}
	}*/
	
	@Override
	public Long findDatabaseSubPrimaryKeyIndex()
	{
		try
		{
			
			Long result = (Long)em
					.createQuery(
							"select max(ordonance_nummer) from OrdonanceTBL o ").getSingleResult();
			
			return result.longValue();
		}
		catch (Exception e)
		{
			/*throw new RuntimeException("OrdonanceTBL is empty",
					e);*/
			return -1l;
		}
	}

}
